import NavBar from '@/components/NavBar'
import { List, Popup, DatePicker, Dialog } from 'antd-mobile'
import styles from './index.module.scss'
import { useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import {
  getUserInfoSync,
  editUserSync,
  editUserInfoSync,
  editPhoto,
  delProfile,
} from '@/store/actions/profile'
import { logout } from '@/store/actions/login'
import EditInput from './EditInput'
import EditList from './EditList'
import { error, success } from '@/utils/tools'
import { uploadAvatarApi } from '@/api/user'
import dayjs from 'dayjs'
import { useNavigate } from 'react-router-dom'
import { Config, EditUser, User, UserAction, UserInfo } from '@/types/user'
import { RootState } from '@/store'
const ProfileEdit = () => {
  const dispatch = useDispatch()
  const navigate = useNavigate()
  // 获取个人基本资料存放到redux中
  useEffect(() => {
    ;(async () => {
      try {
        await dispatch(getUserInfoSync() as unknown as UserAction)
      } catch {}
    })()
  }, [dispatch])
  // 从redux中获取用户基本资料和个人自己的信息
  const { user, userinfo } = useSelector<RootState, RootState['profile']>(
    (state) => state.profile
  )

  // 控制昵称和自我介绍的弹层的显示和隐藏
  const [inputVisible, setInputVisible] = useState({
    visible: false,
    // 控制修改是昵称还是自我介绍
    type: 'name',
    // 控制EditInpu组件要显示的数据
    value: '',
  })
  // 接收昵称和自我介绍的提交信息进行修改
  const handleCommit = async (obj: EditUser) => {
    await dispatch(editUserSync(obj) as unknown as UserAction)
    success('编辑成功', () => {
      setInputVisible({
        type: '',
        visible: false,
        value: '',
      })
    })
  }

  // 修改头像和性别
  const handleUpdateList = async (obj: EditUser) => {
    await dispatch(editUserInfoSync(obj) as unknown as UserAction)
    success('编辑成功', () => {
      setListVisible({
        ...listVisible,
        visible: false,
      })
    })
  }

  // 头像和性别
  // 控制头像和性别的弹层的显示和隐藏
  const [listVisible, setListVisible] = useState({
    visible: false,
    // 控制修改是昵称还是自我介绍
    type: '',
  })

  // 提供给列表组件选项的配置项
  const config: Config = {
    photo: [
      {
        title: '拍照',
        onClick: () => {
          // 点击拍照的div，手动触发文件上传的点击事件
          fileRef.current!.click()
        },
      },
      {
        title: '本地选择',
        onClick: () => {
          // 点击拍照的div，手动触发文件上传的点击事件
          fileRef.current!.click()
        },
      },
    ],
    gender: [
      {
        title: '男',
        onClick: () => {
          handleUpdateList({ gender: 0 })
        },
      },
      {
        title: '女',
        onClick: () => {
          handleUpdateList({ gender: 1 })
        },
      },
    ],
  }

  // 关闭弹层
  const handleClose = () => {
    setListVisible({
      ...listVisible,
      visible: false,
    })
  }
  // 上传图片对象
  const fileRef = useRef<HTMLInputElement>(null)
  // 进行文件上传
  const onAvatarChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    // 获取上传到本地的图片对象
    const files = e.target.files!
    if (files.length === 0) {
      return error('请至少选中一个文件进行上传')
    }
    const file = files[0]
    // 类型
    if (!['image/png', 'image/jpeg', 'image/gif'].includes(file.type)) {
      return error('请选择图片类型进行上传')
    }
    const formData = new FormData()
    formData.append('photo', file)
    // 发送请求
    const { data } = await uploadAvatarApi(formData)
    // 触发redux中的action
    await dispatch(editPhoto(data))
    success('更新成功', () => {
      setListVisible({
        ...listVisible,
        visible: false,
      })
    })
  }

  // 生日
  // 控制生日的时间选择组件的显示和隐藏
  const [birthdayVisible, setBirthdayVisible] = useState(false)

  // 退出登录
  const logoutHandler = () => {
    Dialog.confirm({
      title: '温馨提示',
      content: '您确定要退出登录吗?',
      cancelText: '取消',
      confirmText: '退出',
      onConfirm: async () => {
        await dispatch(delProfile())
        dispatch(logout())
        success('退出成功', () => {
          navigate('/login')
        })
      },
      onCancel: () => {
        console.log('取消')
      },
    })
  }

  return (
    <div className={styles.root}>
      <div className="content">
        {/* 顶部导航栏 */}
        <NavBar>个人信息</NavBar>

        <div className="wrapper">
          {/* 列表一：显示头像、昵称、简介 */}
          <List className="profile-list">
            <List.Item
              extra={
                <span className="avatar-wrapper">
                  <img src={user.photo} alt="" />
                </span>
              }
              onClick={() => {
                setListVisible({
                  type: 'photo',
                  visible: true,
                })
              }}
            >
              头像
            </List.Item>

            <List.Item
              extra={user.name}
              onClick={() => {
                setInputVisible({
                  visible: true,
                  type: 'name',
                  value: user.name!,
                })
              }}
            >
              昵称
            </List.Item>

            <List.Item
              extra={<span className="intro">{user.intro}</span>}
              onClick={() => {
                setInputVisible({
                  visible: true,
                  type: 'intro',
                  value: user.intro!,
                })
              }}
            >
              简介
            </List.Item>
          </List>

          {/* 列表二：显示性别、生日 */}
          <List className="profile-list">
            <List.Item
              extra={userinfo?.gender ? '女' : '男'}
              onClick={() => {
                setListVisible({
                  type: 'gender',
                  visible: true,
                })
              }}
            >
              性别
            </List.Item>
            <List.Item
              onClick={() => {
                setBirthdayVisible(true)
              }}
              extra={userinfo?.birthday}
            >
              生日
            </List.Item>
          </List>

          {/* 文件选择框，用于头像图片的上传 */}
          <input
            ref={fileRef}
            type="file"
            style={{ display: 'none' }}
            onChange={onAvatarChange}
          />
        </div>

        {/* 底部栏：退出登录按钮 */}
        <div className="logout">
          <button className="btn" onClick={logoutHandler}>
            退出登录
          </button>
        </div>
      </div>
      {/* 修改昵称和自我介绍的弹出层 */}
      <Popup
        visible={inputVisible.visible}
        position="right"
        bodyStyle={{ width: '100vw' }}
      >
        <EditInput
          onLeftClick={() =>
            setInputVisible({
              value: '',
              visible: false,
              type: '',
            })
          }
          type={inputVisible.type as 'name' | 'intro'}
          onCommit={handleCommit}
        ></EditInput>
      </Popup>
      {/* 修改头像和性别的弹出层 */}
      <Popup
        visible={listVisible.visible}
        onMaskClick={handleClose}
        onClose={handleClose}
      >
        <EditList
          config={config}
          type={(listVisible.type as 'photo') || 'gender'}
          onClose={handleClose}
        ></EditList>
      </Popup>
      {/* 修改生日 */}
      <DatePicker
        visible={birthdayVisible}
        title="选择生日"
        renderLabel={(type, data) => {
          switch (type) {
            case 'year':
              return data + '年'
            case 'month':
              return data + '月'
            case 'day':
              return data + '日'
            default:
              return data
          }
        }}
        value={new Date(userinfo?.birthday!)}
        max={new Date()}
        min={new Date('1990-1-1')}
        onConfirm={async (val) => {
          // 将从 DatePicker 组件获取到的 Date 对象，转成字符串的形式
          const birthday = dayjs(val).format('YYYY-MM-DD')
          await dispatch(
            editUserInfoSync({ birthday }) as unknown as UserAction
          )
          success('编辑成功', () => {
            setBirthdayVisible(false)
          })
        }}
        onClose={() => {
          setBirthdayVisible(false)
        }}
      />
    </div>
  )
}

export default ProfileEdit
